package com.kaikai.msg.channel;

import com.kaikai.commonutils.BaseConstant;
import com.kaikai.commonutils.JsonUtil;
import com.kaikai.config.ChannelConstant;

import com.kaikai.msg.model.ao.EduEmail;
import com.kaikai.msg.utils.MsgSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import com.kaikai.msg.model.dto.SendMailDTO;

/**
 * 消息监听
 */
@EnableBinding(value = EmailMsgChannel.class)
@Component
public class EmailMsgListener {

    @Autowired
    private MsgSender msgSender;

    /*
     * @param msg
     * @return void
     * @Author yujiankai
     * @Description 邮件渠道监听
     * @date 2022/1/6 16:26
     */
    @StreamListener(value = ChannelConstant.EMAIL_DEFAULT_CHANNEL)
    public void receiverEmailMsg(@Payload String msg) throws Exception {
        EduEmail eduEmail = JsonUtil.convertJsonToObject(msg, EduEmail.class);
        try {
            SendMailDTO.sendMail(eduEmail);
            eduEmail.setSendRslt(BaseConstant.MSG_SEND_SUCCESS);
        } catch (Exception e) {
            eduEmail.setSendRslt(BaseConstant.MSG_SEND_ERROR);
            eduEmail.setSendFailReason(e.getMessage());
            System.out.println("邮件发送失败：");
            e.printStackTrace();
        }
        //消息回执推送
        msgSender.sendMessage(eduEmail, ChannelConstant.EMAIL_RECEIPT_CHANNEL);
    }

}
